package com.course.controller.permission;

import android.app.Activity;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class PermissionManager {


    private static PermissionManager manager;

    public static PermissionManager getManager() {
        if (manager == null) {
            manager = new PermissionManager();
        }
        return manager;
    }

    public boolean requestSinglePermission(Activity activity, String permissions, int requestCode) {
        if (StringUtils.isBlank(permissions)) {
            return true;
        }
        return requestPermissions(activity, new String[]{permissions}, requestCode);
    }


    public boolean requestPermissions(Activity activity, String[] permissions, int requestCode) {
        if (permissions == null || permissions.length == 0) {
            return true;
        }
        List<String> permission = new ArrayList<>();
        for (String per : permissions) {
            if (!grantedPermission(activity, per)) {
                permission.add(per);
            }
        }

        if (permission.size() == 0) {
            return true;
        }

        String[] array = new String[permission.size()];
        permission.toArray(array);
        ActivityCompat.requestPermissions(activity,
                array,
                requestCode);
        return false;
    }


    public boolean grantedPermission(Activity activity, String permission) {
        if (ContextCompat.checkSelfPermission(activity,
                permission)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }


}
